'use strict';

const Controller = require('egg').Controller;
const jwt = require("jsonwebtoken");
const Axios = require("axios");
const client_id = "3400cccebf48fae463f54a342e0c8a6b3c158a2f44081c6b07f1a767b7875f3c";
const client_secret = "bb1a663996368a79cc124af22538cedae86eaaeb47bec94334fec1f5fb3909ca";
const redirect_uri = "http://127.0.0.1:7001/api/oauth/redirect";
//引入验证码
const SvgCaptcha = require("svg-captcha")
class HomeController extends Controller {
  //查找数据
  async GETMock() {
    const { ctx, app } = this;
    const data = await app.mysql.select("data");
    ctx.body = {
      code: 200,
      message: "发送成功",
      data: data,
    };
  }
  async Login() {
    const { ctx, app } = this;
    const { phone, password } = ctx.request.body;
    const data = await app.mysql.get("login", {
      phone,
      password,
    });
    if (!data) {
      ctx.body = {
        code: 200,
        message: "请注册",
      };
    } else {
      const token = jwt.sign({ ...data, password: "" }, "1904A", {
        expiresIn: "24",
      });
      ctx.body = {
        code: 200,
        message: "登录成功",
        token,
      };
    }
  }
  //注册
  async Register() {
    const { ctx, app } = this;
    const { phone, nickname, password = "", avatar, email } = ctx.request.body;
    const data = await app.mysql.insert("login", {
      phone,
      nickname,
      password,
      avatar,
      email,
    });
    if(data.affectedRows){
      ctx.body = {
        code:200,
        message:"注册成功",
      }
    }else{
      ctx.body = {
        code:404,
        message:"注册失败"
      }
    }
  }
  //验证码
  async getCode(){
    const {ctx} = this;
    const options = {
      size:4,
      fontSize:50,
      width:100,
      height:30,
      color:true,
    }
    const cap = SvgCaptcha.create(options);
    ctx.session.code = cap.text;
    ctx.body = {
      code:200,
      message:"验证码获取成功",
      data:cap.data
    }
  }
}

module.exports = HomeController;
